import Vue from 'vue'
import VueI18n from 'vue-i18n'
import elementEnLocale from 'element-ui/lib/locale/lang/en'
import elementZhCNLocale from 'element-ui/lib/locale/lang/zh-CN'
import elementZhTWLocale from 'element-ui/lib/locale/lang/zh-TW'
import { getAuthLanguage, setAuthLanguage } from '../utils/browser'
import ElementLocale from 'element-ui/lib/locale'

import enLocale from './mapping/en'
import zhCNLocale from './mapping/zh-cn'
import zhTWLocale from './mapping/zh-tw'

Vue.use(VueI18n)

const messages = {
  en: {
    ...enLocale,
    ...elementEnLocale
  },
  'zh-cn': {
    ...zhCNLocale,
    ...elementZhCNLocale
  },
  'zh-tw': {
    ...zhTWLocale,
    ...elementZhTWLocale
  }
}
// 根据language获取多语言字段的映射属性名
export function getLangMappingProperty(lang, basePrefix) {
  let langMappingProperty = ''
  switch (lang) {
    case 'en':
      langMappingProperty = basePrefix + 'En'
      break
    case 'zh-cn':
      langMappingProperty = basePrefix + 'ZhCn'
      break
    case 'zh-tw':
      langMappingProperty = basePrefix + 'ZhTw'
      break
    default:
      langMappingProperty = basePrefix + 'En'
      break
  }
  return langMappingProperty
}

export function initLanguage() {
  const chooseLanguage = getAuthLanguage()
  if (chooseLanguage) {
    return chooseLanguage
  }
  // 不存在则默认中文
  setAuthLanguage('zh-cn')
  return 'zh-cn'
}

const i18n = new VueI18n({
  locale: initLanguage(),
  messages
})

ElementLocale.i18n((key, value) => i18n.t(key, value))

export default i18n
